import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, register, getUserInfo } from '@/api/user'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const refreshToken = ref(localStorage.getItem('refreshToken') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))
  const roles = ref(JSON.parse(localStorage.getItem('roles') || '[]'))
  const permissions = ref(JSON.parse(localStorage.getItem('permissions') || '[]'))
  const menus = ref(JSON.parse(localStorage.getItem('menus') || '[]'))
  
  // 初始化用户信息（从本地存储加载）
  const initUserInfo = () => {
    const storedToken = localStorage.getItem('token')
    const storedRefreshToken = localStorage.getItem('refreshToken')
    const storedUserInfo = localStorage.getItem('userInfo')
    const storedRoles = localStorage.getItem('roles')
    const storedPermissions = localStorage.getItem('permissions')
    const storedMenus = localStorage.getItem('menus')
    
    // 加载本地缓存
    if (storedToken) {
      token.value = storedToken
    }
    if (storedRefreshToken) {
      refreshToken.value = storedRefreshToken
    }
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
      } catch (e) {
        console.error('解析用户信息失败', e)
        userInfo.value = null
      }
    }
    if (storedRoles) {
      try {
        roles.value = JSON.parse(storedRoles)
      } catch (e) {
        console.error('解析角色信息失败', e)
        roles.value = []
      }
    }
    if (storedPermissions) {
      try {
        permissions.value = JSON.parse(storedPermissions)
      } catch (e) {
        console.error('解析权限信息失败', e)
        permissions.value = []
      }
    }
    if (storedMenus) {
      try {
        menus.value = JSON.parse(storedMenus)
      } catch (e) {
        console.error('解析菜单信息失败', e)
        menus.value = []
      }
    }
  }

  // 登录
  const userLogin = async (loginData) => {
    try {
      const res = await login(loginData)
      if (res.code === 200) {
        token.value = res.data.token
        refreshToken.value = res.data.refreshToken || ''
        userInfo.value = res.data.userInfo
        
        // 保存token和基本信息
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('refreshToken', res.data.refreshToken || '')
        localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo))
        
        // 获取完整的用户信息（角色、权限、菜单）
        await fetchUserFullInfo(res.data.userInfo.id)
        
        ElMessage.success('登录成功')
        router.push('/home')
      } else {
        ElMessage.error(res.message || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error(error.message || '登录失败，请稍后重试')
    }
  }

  // 注册
  const userRegister = async (registerData) => {
    try {
      const res = await register(registerData)
      if (res.code === 200) {
        ElMessage.success('注册成功，请登录')
        router.push('/login')
      } else {
        ElMessage.error(res.message || '注册失败')
      }
    } catch (error) {
      console.error('注册失败:', error)
      ElMessage.error(error.message || '注册失败，请稍后重试')
    }
  }

  // 获取用户完整信息
  const fetchUserFullInfo = async (userId) => {
    try {
      const res = await getUserInfo(userId)
      if (res.code === 200) {
        const data = res.data
        
        // 更新状态
        userInfo.value = data.userInfo
        roles.value = data.roles || []
        permissions.value = Array.from(data.permissions || [])
        menus.value = data.menus || []
        
        // 保存到本地存储
        localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
        localStorage.setItem('roles', JSON.stringify(data.roles || []))
        localStorage.setItem('permissions', JSON.stringify(Array.from(data.permissions || [])))
        localStorage.setItem('menus', JSON.stringify(data.menus || []))
      }
    } catch (error) {
      console.error('获取用户完整信息失败:', error)
    }
  }

  // 退出登录
  const logout = async (showMessage = true) => {
    // 如果有token，尝试调用后端登出接口
    if (token.value) {
      try {
        await fetch('http://localhost:8080/api/auth/logout', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token.value}`
          }
        })
      } catch (error) {
        // 登出接口失败不影响客户端登出
        console.error('登出接口调用失败:', error)
      }
    }
    
    // 清除所有状态
    token.value = ''
    refreshToken.value = ''
    userInfo.value = null
    roles.value = []
    permissions.value = []
    menus.value = []
    
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('roles')
    localStorage.removeItem('permissions')
    localStorage.removeItem('menus')
    
    // 根据参数决定是否显示提示
    if (showMessage) {
      ElMessage.success('已退出登录')
    }
    
    // 只有不在登录页时才跳转
    const currentPath = router.currentRoute.value.path
    if (currentPath !== '/login' && currentPath !== '/register') {
      router.push('/login')
    }
  }

  // 检查是否有指定权限
  const hasPermission = (permission) => {
    return permissions.value.includes(permission)
  }

  // 检查是否有指定角色
  const hasRole = (roleKey) => {
    return roles.value.some(role => role.roleKey === roleKey)
  }

  // 检查是否是管理员
  const isAdmin = () => {
    return hasRole('admin')
  }

  // 刷新用户权限和菜单（手动刷新，显示提示）
  const refreshUserPermissions = async () => {
    if (!userInfo.value || !userInfo.value.id) {
      ElMessage.warning('请先登录')
      return false
    }
    
    try {
      await fetchUserFullInfo(userInfo.value.id)
      ElMessage.success('权限信息已刷新')
      return true
    } catch (error) {
      console.error('刷新用户权限失败:', error)
      ElMessage.error('刷新权限失败，请稍后重试')
      return false
    }
  }

  // 刷新Access Token
  const refreshAccessToken = async () => {
    try {
      const res = await fetch('http://localhost:8080/api/auth/refresh', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          refreshToken: refreshToken.value
        })
      })
      
      const data = await res.json()
      
      if (data.code === 200) {
        token.value = data.data.token
        refreshToken.value = data.data.refreshToken
        localStorage.setItem('token', data.data.token)
        localStorage.setItem('refreshToken', data.data.refreshToken)
        console.log('Token刷新成功')
        return true
      } else {
        console.error('Token刷新失败:', data.message)
        // Token刷新失败，静默清除登录状态（不显示提示）
        await logout(false)
        return false
      }
    } catch (error) {
      console.error('Token刷新异常:', error)
      // Token刷新异常，静默清除登录状态（不显示提示）
      await logout(false)
      return false
    }
  }

  return {
    token,
    refreshToken,
    userInfo,
    roles,
    permissions,
    menus,
    initUserInfo,
    userLogin,
    userRegister,
    logout,
    fetchUserFullInfo,
    refreshUserPermissions,
    refreshAccessToken,
    hasPermission,
    hasRole,
    isAdmin
  }
})